package com.aicloud.gateway.aggregation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.aicloud.gateway.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import rx.Observable;

/**
 * 电影服务和用户服务的服务聚合类
 * 
 * @author aaron
 * @varsion 0.1.0 2017年10月29日
 */
@Service
public class MoviesAndUsersAggregationService {
	private static final String	USER_SERVICE_URL		= "http://aicloud-users/user/";
	private static final String	MOVIES_USER_SERVICE_URL	= "http://aicloud-movies/feign/user/";

	@Autowired
	RestTemplate				restClient;

	/**
	 * 获取用户信息
	 * 
	 * @param id
	 * @return
	 */
	@HystrixCommand(fallbackMethod = "fallback")
	public Observable<User> getUserById(Long id) {
		// 创建一个被观察者
		return Observable.create(observer -> {
			User user = restClient.getForObject(USER_SERVICE_URL + "{id}", User.class, id);
			observer.onNext(user);
			observer.onCompleted();
		});
	}

	/**
	 * 获取电影微服务用户信息
	 * 
	 * @param id
	 * @return
	 */
	@HystrixCommand(fallbackMethod = "fallback")
	public Observable<User> getMovieUserById(Long id) {
		// 创建一个被观察者
		return Observable.create(observer -> {
			User user = restClient.getForObject(MOVIES_USER_SERVICE_URL + "{id}", User.class, id);
			observer.onNext(user);
			observer.onCompleted();
		});
	}

	/**
	 * 降级服务
	 * 
	 * @param id
	 * @return
	 */
	public User fallback(Long id) {
		User user = new User();
		user.setId(-1L);
		user.setName("聚合服务降级");
		return user;
	}
}
